package com.tpo.jnotes.client.layer.model;

import java.util.List;

import org.hibernate.Criteria;

import com.tpo.jnotes.client.layer.model.entity.ENote;
import com.tpo.jnotes.client.layer.model.util.NHibernateUtil;
import com.tpo.jnotes.client.lib.interfaces.IModel;
import com.tpo.jnotes.client.lib.interfaces.IModelEntity;
import com.tpo.jnotes.client.main.Logging;

public class NModel implements IModel
{

    public NModel()
    {
    }

    @Override
    public List< IModelEntity > getEntities()
    {
        return doQuery();
    }

    @Override
    public IModelEntity addEntity()
    {
        ENote newNote = new ENote();
        Logging.info( "Model > save note: " + newNote.getId() );
        NHibernateUtil.getSession().save( newNote );
        NHibernateUtil.commit();
        return newNote;
    }

    @Override
    public void deleteEntity( int id )
    {
        Logging.info( "Model > save note: " + id );
        NHibernateUtil.getSession().delete( getEntity( id ) );
        NHibernateUtil.commit();
    }

    private List< IModelEntity > doQuery()
    {
        Criteria criteria = NHibernateUtil.getSession().createCriteria( ENote.class );
        // criteria.add(Restrictions.like("RO", "A%").ignoreCase());
        List< IModelEntity > subsList = criteria.list();
        return subsList;
    }

    @Override
    public void update()
    {
        NHibernateUtil.commit();
    }

    @Override
    public IModelEntity getEntity( int id )
    {
        return (IModelEntity)NHibernateUtil.getSession().get( ENote.class, id );
    }

    @Override
    public void setProperty( int id, String propertyName, Object propertyValue )
    {
        Logging.trace( "Model > set property " + propertyName + " = " + propertyValue + " for id " + id );
        getEntity( id ).setProperty( propertyName, propertyValue );
    }
}
